package com.seven.spring;

import java.beans.Introspector;
import java.io.File;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.net.URL;
import java.util.ArrayList;
import java.util.concurrent.ConcurrentHashMap;

public class SevenSpringApplicationContext {

    /**
     * spring配置类，包含 1.包扫描路径
     */
    private Class configClass;
    /**
     * bean定义的集合
     */
    private ConcurrentHashMap<String, BeanDefinition> beanDefinitionMap = new ConcurrentHashMap<>();
    /**
     * 单例池
     */
    private ConcurrentHashMap<String, Object> singletonObjects = new ConcurrentHashMap<>();

    private ArrayList<BeanPostProcessor> beanPostProcessorList = new ArrayList<>();

    public SevenSpringApplicationContext(Class configClass) {
        this.configClass = configClass;
        //扫描
        /**
         * 判断configClass身上有没有ComponentScan注解
         * 如果有，则解析到注解带的包名
         * 注意扫描的是class文件，Target目录下面的
         */
        if (configClass.isAnnotationPresent(ComponentScan.class)) {
            ComponentScan componentScanAnnotation = (ComponentScan) configClass.getAnnotation(ComponentScan.class);
            String path = componentScanAnnotation.value();//扫描路径 com.seven.service
            path = path.replace(".", "/");// com/seven/service
            ClassLoader classLoader = SevenSpringApplicationContext.class.getClassLoader();
            URL resource = classLoader.getResource(path);
            File file = new File(resource.getFile());
            System.out.println(file);
            if (file.isDirectory()) {
                File[] files = file.listFiles();
                for (File f : files) {
                    String fileName = f.getAbsolutePath();
//                    System.out.println(fileName);
                    if (fileName.endsWith(".class")) {
                        String className = fileName.substring(fileName.indexOf("com"), fileName.indexOf(".class"));
                        className = className.replace("\\", ".");
//                        System.out.println(className);
                        try {
                            //对于类加载器，加载一个类，是需要类的全限定名com.seven.UserService
                            Class<?> clazz = classLoader.loadClass(className);
                            //只有包含Componet注解的才是Bean
                            if (clazz.isAnnotationPresent(Component.class)) {

                                //判断clazz（类）是否实现这个接口
                                if (BeanPostProcessor.class.isAssignableFrom(clazz)) {
                                    BeanPostProcessor instance = (BeanPostProcessor) clazz.newInstance();
                                    beanPostProcessorList.add(instance);
                                }

                                Component component = clazz.getAnnotation(Component.class);
                                String beanName = component.value();
                                if (beanName.equals("")) {
                                    //jdk默认方法，把首字母小写，如果前两个都大写，就直接返回
                                    beanName = Introspector.decapitalize(clazz.getSimpleName());
                                }

                                //1.创建BeanDefinition对象
                                BeanDefinition beanDefinition = new BeanDefinition();
                                beanDefinition.setType(clazz);
                                if (clazz.isAnnotationPresent(Scope.class)) {
                                    Scope scopeAnnotation = clazz.getAnnotation(Scope.class);
                                    beanDefinition.setScope(scopeAnnotation.value());
                                } else {
                                    //单例是默认的，不传默认单例
                                    beanDefinition.setScope("singleton");
                                }
                                beanDefinitionMap.put(beanName, beanDefinition);
                            }
                        } catch (ClassNotFoundException e) {
                            e.printStackTrace();
                        } catch (InstantiationException e) {
                            throw new RuntimeException(e);
                        } catch (IllegalAccessException e) {
                            throw new RuntimeException(e);
                        }
                    }
                }
            }
        }
        //生成单例bean
        /**
         *对于多例的bean，只有到需要使用时才创建
         */
        for (String beanName : beanDefinitionMap.keySet()) {
            BeanDefinition beanDefinition = beanDefinitionMap.get(beanName);
            if (beanDefinition.getScope().equals("singleton")) {
                Object bean = createBean(beanName, beanDefinition);
                singletonObjects.put(beanName, bean);
            }
        }
    }

    private Object createBean(String beanName, BeanDefinition beanDefinition) {
        Class clazz = beanDefinition.getType();

        try {
            //反射创建bean
            Object instance = clazz.getConstructor().newInstance();
            //依赖注入
            for (Field f : clazz.getDeclaredFields()) {
                if (f.isAnnotationPresent(Autowired.class)) {
                    f.setAccessible(true);
                    //类似于一个递归的创建bean
                    f.set(instance, getBean(f.getName()));
                }
            }
            /**
             * spring创建完bean之后会，调一系列的回调
             * 回调就是spring预先定义了一系列接口，当我们的bean实现了这些接口，
             * spring会主动调用这些接口内的方法，不需要关心入参的来源。
             */
            //BeanName的Aware回调
            //判断对象是否实现了这个接口
            if (instance instanceof BeanNameAware) {
                ((BeanNameAware) instance).setBeanName(beanName);
            }

            //初始化前
            for (BeanPostProcessor beanPostProcessor : beanPostProcessorList) {
                instance=beanPostProcessor.postProcessBeforeInitialization(beanName,instance);
            }

            //初始化
            if (instance instanceof InitializaingBean) {
                ((InitializaingBean) instance).afterPropertiesSet();
            }

            //初始化后
            for (BeanPostProcessor beanPostProcessor : beanPostProcessorList) {
                instance=beanPostProcessor.postProcessAfterInitialization(beanName,instance);
            }
            /**
             * spring调完回调之后则会执行AOP
             */



            return instance;
        } catch (InstantiationException e) {
            throw new RuntimeException(e);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        } catch (InvocationTargetException e) {
            throw new RuntimeException(e);
        } catch (NoSuchMethodException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 创建bean
     * 通过这段源码了解到，spring对于所有的bean都会有一个beandfineantion对象
     * 但是它会首先创建单例的bean
     * 对于多例的bean，只有到需要使用时才创建
     *
     * @param beanName
     * @return
     */
    public Object getBean(String beanName) {
        BeanDefinition beanDefinition = beanDefinitionMap.get(beanName);
        if (beanDefinition == null) {
            throw new NullPointerException();
        } else {
            String scope = beanDefinition.getScope();
            if (scope.equals("singleton")) {
                //单例
                Object bean = singletonObjects.get(beanName);
                /**
                 * 为什么存在在单例池中找不到的例子，
                 * 可能先扫到A类，然后B被A引用，getBean（A）的时候就有可能找不到B
                 */
                if (bean == null) {
                    bean = createBean(beanName, beanDefinition);
                    singletonObjects.put(beanName, bean);
                }
                return bean;
            } else {
                //多例
                return createBean(beanName, beanDefinition);
            }
        }
    }
}
